package cn.itheima.controller;

import cn.itheima.pojo.Result;
import cn.itheima.pojo.User;
import cn.itheima.service.UserService;
import cn.itheima.utils.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.Pattern;

/**
 * @author 董代恒
 * @version 1.0
 */
@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 注册接口
     *
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/register")
    public Result register(@Pattern(regexp = "\\S{5,16}$") String username, @Pattern(regexp = "\\S{5,16}$") String password) {
        /*
            注册需要数据校验
            \S:匹配所有非空字符
            $:匹配一行的结尾
            "\\S{5,16}$":这个正则表达式就是匹配5到16个字符
         */
        User u = userService.findByUsername(username);
        if (u == null) {
            //注册
            userService.register(username, password);
            return Result.success();
        } else {
            //用户名已存在
            return Result.error("用户名已存在");
        }
    }

    @PostMapping("/login")
    public Result login(@Pattern(regexp = "\\S{5,16}$") String username, String password) {
        //1.判断用户名是否存在
        User u = userService.findByUsername(username);
        if (u==null){
            return Result.error("用户名不存在");
        }
        //判断数据库里面的加密密码
        if (Md5Util.getMD5String(password).equals(u.getPassword())){
            return Result.success("JWT Token","登录成功");
        }

        return Result.error("登录失败");
    }

}
